package main

import (
	"fmt"
	"os"
	"path"
	"strings"

	"github.com/iancoleman/strcase"
)

func main() {
	doCommand(os.Args[1:])
}

func doCommand(args []string) {
	if len(args) < 2 || args[0] == "-h" {
		showHelp()
		return
	}

	from := args[0]
	to := args[1]

	var newName string

	if to[0] == '.' {
		newName = doRenameExt(from, to)
	} else if to[0] == ':' {
		newName = doTransform(from, to, args)
	} else {
		newName = doRename(from, to)
	}

	err := os.Rename(from, newName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(2)
	}

}

func showHelp() {
	fmt.Println("Usage: $ rename [from] [to] [options...]")
}

// rename a.txt .mp3 will rename a.txt to a.mp3
func doRenameExt(from, to string) string {
	dir := path.Dir(from)
	basename := path.Base(from)

	part := strings.Split(basename, ".")[0]
	newExt := to

	return dir + "/" + part + newExt
}

func doTransform(from, to string, args []string) string {
	dir := path.Dir(from)
	basename := path.Base(from)
	ext := path.Ext(basename)

	// if a.txt, part = a
	part := strings.Split(basename, ".")[0]

	switch to {
	case ":upper":
		part = strings.ToUpper(part)
	case ":lower":
		part = strings.ToLower(part)
	case ":camel":
		part = strcase.ToCamel(part)
	case ":snake":
		part = strcase.ToSnake(part)
	case ":plus":
		if len(args) == 3 {
			suffix := args[2]
			part = part + suffix
		}
	}

	return dir + "/" + part + ext
}

func doRename(from, to string) string {
	dir := path.Dir(from)

	basename := path.Base(from)
	ext := path.Ext(basename)

	return dir + "/" + to + ext
}
